﻿using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Windows.Admin.Domain;
using Windows.Admin.Infrastructure.EFCore;
using Windows.Infrastructure.EFCore.Share.Extensions;
using Windows.Infrastructure.Share.CustomException;
using Windows.Infrastructure.Share.Extensions;
using Windows.Infrastructure.Share.Tools;
using Windows.Service.Share;

namespace Windows.Admin.Service
{
    public class RoleService : IRoleService
    {
        private readonly IMapper _mapper;
        //private readonly ICache _cache;
        private readonly AdminDbContext _db;
        public RoleService(IMapper mapper, AdminDbContext db)
        {
            _mapper = mapper;
            _db = db;
        }
        /// <summary>
        /// 获取所有角色
        /// </summary>
        /// <returns></returns>
        public async Task<List<RoleResponse>> GetBasicRoles(IdsRequest request)
        {
            var query =  _db.Role.Where(x => x.Id != ConfigurationUtils.GetSection("DefaultRoleId").ToInt());
            if (request.Ids.Length > 0)
            {
                query = query.OrderByDescending(o => request.Ids.Contains(o.Id));
            }
            var roles = await query.ToListAsync();
            return _mapper.Map<List<RoleResponse>>(roles);
        }
        /// <summary>
        /// 角色视图
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<PageResponse<RoleResponse>> Query(PageRequest<RoleRequest> request)
        {
            var query = Where(request);
            var list = await query.Paging(request.PageIndex, request.PageSize).ToListAsync();
            var response = new PageResponse<RoleResponse>
            {
                TotalCount = await query.CountAsync(),
                PageIndex = request.PageIndex,
                PageSize = request.PageSize,
                List = _mapper.Map<List<RoleResponse>>(list)
            };
            return response;
        }
        /// <summary>
        /// 获取id的角色详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<RoleResponse> Detail(int id)
        {
            var model = await _db.Role.FindByIdAsync(id);
            return _mapper.Map<RoleResponse>(model);
        }
        /// <summary>
        /// 角色保存
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        /// <exception cref="ApiException"></exception>
        public async Task Save(RoleSaveRequest request)
        {
            if (request.Id == ConfigurationUtils.GetSection("AdminRoleId").ToInt())
                throw new ApiException($"超级管理员不允许修改!");
            if (request.Id == ConfigurationUtils.GetSection("DefaultRoleId").ToInt())
                throw new ApiException($"默认用户不允许修改!");

            if (_db.Role.Any(x => x.Code.ToLower() == request.Code && x.Id != request.Id))
                throw new ApiException("角色编码已存在!");
            if (_db.Role.Any(x => x.Name.ToLower() == request.Name && x.Id != request.Id))
                throw new ApiException("角色名称已存在!");
            if (request.Id == null)
            {
                Role model = _mapper.Map<Role>(request);
                await _db.Role.AddAsync(model);
            }
            else
            {
                Role? model = await _db.Role.FindByIdAsync(request.Id.Value);
                if (model == null)
                    throw new ApiException("角色不存在!");
                model.Name = request.Name;
                model.Code = request.Code;
                model.Remark = request.Remark;
            }
            await _db.SaveChangesAsync();
        }
        /// <summary>
        /// 角色删除
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task Remove(IdsRequest request)
        {
            if (request.Ids.Contains(ConfigurationUtils.GetSection("AdminRoleId").ToInt()))
                throw new ApiException($"超级管理员不允许删除!");
            if (request.Ids.Contains(ConfigurationUtils.GetSection("DefaultRoleId").ToInt()))
                throw new ApiException($"默认用户不允许删除!");

            var names = await _db.Role.Include(x => x.Role_Organizations).Include(x => x.Role_Users).Include(x => x.Role_Posts).Where(x => request.Ids.Contains(x.Id) && (x.Role_Organizations.Count > 0 || x.Role_Users.Count > 0 || x.Role_Posts.Count > 0)).Select(s => s.Name).ToListAsync();
            if (names.Count > 0)
            {
                throw new ApiException($"角色:{string.Join(',', names)}已被绑定,不允许删除!");
            }
            await _db.Role.RemoveAsync(request.Ids);
            await _db.SaveChangesAsync();
        }
        /// <summary>
        /// 绑定角色
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        /// <exception cref="ApiException"></exception>
        public async Task BindRoles(BindRolesRequest request)
        {
            var master = request.Master.GetEnum<RoleMasterEnum>();
            if (master == RoleMasterEnum.User)
            {
                var model = await _db.User.Include(x => x.Role_Users).FindByIdAsync(request.Id) ?? throw new ApiException("用户不存在!");
                //删除角色列表(除了默认用户角色)
                model.Role_Users = model.Role_Users.Where(x => x.RoleId == ConfigurationUtils.GetSection("DefaultRoleId").ToInt()).ToList();
                if (request.RoleIds != null)
                {
                    foreach (long roleId in request.RoleIds)
                    {
                        Role_User role_User = new()
                        {
                            RoleId = roleId,
                        };
                        model.Role_Users.Add(role_User);
                    }
                }
            }
            else if (master == RoleMasterEnum.Organization)
            {
                var model = await _db.Organization.Include(x => x.Role_Organizations).FindByIdAsync(request.Id) ?? throw new ApiException("组织机构不存在!");
                //删除角色列表
                _db.RemoveRange(model.Role_Organizations);
                if (request.RoleIds != null)
                {
                    foreach (long roleId in request.RoleIds)
                    {
                        Role_Organization role_Organization = new()
                        {
                            RoleId = roleId,
                        };
                        model.Role_Organizations.Add(role_Organization);
                    }
                }
            }
            else if (master == RoleMasterEnum.Post)
            {
                var model = await _db.Post.Include(x => x.Role_Posts).FindByIdAsync(request.Id) ?? throw new ApiException("岗位不存在!");
                //删除角色列表
                _db.RemoveRange(model.Role_Posts);
                if (request.RoleIds != null)
                {
                    foreach (long roleId in request.RoleIds)
                    {
                        Role_Post role_Post = new()
                        {
                            RoleId = roleId,
                        };
                        model.Role_Posts.Add(role_Post);
                    }
                }
            }
            await _db.SaveChangesAsync();
        }
        private IQueryable<Role> Where(PageRequest<RoleRequest> request)
        {
            IQueryable<Role> query = _db.Role.AsQueryable();
            if (!request.Query.Name.IsNullOrWhiteSpace())
            {
                query = query.Where(x => x.Name.Contains(request.Query.Name!));
            }
            return query;
        }
    }
}
